import type { Slide } from '@/types/slides'
import { GetTemplateItemData } from './checkTemplate'
import { cloneDeep } from 'lodash'
import { nanoid } from 'nanoid'

export async function GetDirCourseware(tempId: string, dirs: string[]): Promise<Slide | undefined> {
  const tempData = await GetTemplateItemData(tempId, 'dir')
  if (!tempData) return

  const { container, item, itemStep } = tempData.default
  const box = cloneDeep(container)

  for (let i = 0; i < dirs.length; i++) {
    let dirStr = JSON.stringify(item)
    const dir = dirs[i]
    const idx: string = i >= 9 ? `${i + 1}` : `0${i + 1}`
  
    const curLine = Math.floor(i / itemStep.line)
    const line = i % itemStep.line
  
    const leftStep = line * itemStep.left
    const topStep = curLine * itemStep.top
  
    dirStr = dirStr.replace('%幻灯片目录%', dir)
    dirStr = dirStr.replace('%幻灯片目录序号%', idx)
    
    const dirItem = JSON.parse(dirStr)
  
    dirItem.forEach((el: any) => {
      el.id = nanoid(10)
      el.left += leftStep
      el.top += topStep
    })
  
    box.elements.push(...dirItem)
  }

  box.id = nanoid(10)
  return box
}